package edu.upf.da.p2p.sm.server.manager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;

import edu.upf.da.p2p.sm.P2PClient;
import edu.upf.da.p2p.sm.client.message.ServiceDefinition;


public class PresenceManager implements PacketListener {

	private static final Log log = LogFactory.getLog(PresenceManager.class);

	private P2PClient imc;
	private String weAre;
	private boolean announce;
	private AuthManager authManager;

	public PresenceManager(P2PClient client, String string) {
		this.imc = client;
		weAre = string;
		announce = true;
	}

	public void linkTo(AuthManager authListener) {
		authManager = authListener;
	}

	public void processPacket(Packet pkt) {
		try{
			Presence p = (Presence) pkt;
			if(authManager != null && !p.isAvailable()){
				authManager.broadcastUserGranted("", p.getFrom());
				if(log.isTraceEnabled()){
					log.trace("El usuario '"+p.getFrom()+"' ha desconectado y se notifica a todos.");
				}
			}
			if(announce && p.isAvailable()){
				ServiceDefinition sd = new ServiceDefinition(weAre);
				sd.setTo(p.getFrom());
				imc.sendMessage(sd);
				if(log.isTraceEnabled()){
					log.trace("Se ha enviado el service definition a: '"+p.getFrom()+"'.");
				}
			}
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error("Error al recibir un paquete de presencia.",e);
			}
		}
	}

	public void setAnnounce(boolean b){
		announce = b;
	}



}
